package cn.yeyiu.mangaviewer;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;

import java.util.List;

import cn.yeyiu.util.MediaUtil;
import cn.yeyiu.util.bean.MangaEP;
import cn.yeyiu.util.bean.MangaDetail;

public class MangaDetailActivity extends AppCompatActivity {

    private TextView headTitle;
    private TextView bgTitle;

    private ImageView backIV;
    private ImageView epBgIV;

    private GridLayout epsGL;

    private MangaDetail mangaDetail;
    private List<MangaEP> mangaEPs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manga_info);

        initData();
        bindView();
        bindEvent();
        initUI();
        inflateEps();
    }

    void initData() {
        this.mangaDetail = JSONObject.parseObject(getIntent().getStringExtra("mangaDetail"), MangaDetail.class);
        this.mangaEPs = mangaDetail.getEps();
    }

    void bindView() {
        headTitle = findViewById(R.id.back_tv);
        bgTitle = findViewById(R.id.ep_bg_title);
        backIV = findViewById(R.id.back_btn);
        epBgIV = findViewById(R.id.ep_bg);
        epsGL = findViewById(R.id.manga_eps_menu_gl);
    }

    void bindEvent() {
        backIV.setOnClickListener(v -> finish());
    }

    void initUI() {
        headTitle.setText(this.mangaDetail.getTitle());
        bgTitle.setText(this.mangaDetail.getTitle());
        Glide.with(this)
                .load(mangaDetail.getLogo())
                .into(epBgIV);
    }

    void inflateEps() {
        View view;
        int i = 0;
        for (MangaEP ep : mangaEPs) {
            view = LayoutInflater.from(this).inflate(R.layout.item_manga_ep, epsGL, false);
            ((TextView) view.findViewById(R.id.ep_title)).setText(ep.getTitle());
            Glide.with(this)
                    .load(ep.getLogo())
                    .into((ImageView) view.findViewById(R.id.ep_img));
            epsGL.addView(view);

            int epOrder = i;
            view.setOnClickListener(v -> {
                MediaUtil.readMangaEp(MangaDetailActivity.this,
                        MangaViewActivity.class,
                        this.mangaEPs.get(epOrder)
                );
            });
            i++;
        }
    }
}